package com.nf.health.app.sweat.fragment;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.nf.health.app.AfinalDb.MeasureDataDao;
import com.nf.health.app.R;
import com.nf.health.app.customview.SweatShowView;
import com.nf.health.app.fragment.IBaseFragment;
import com.nf.health.app.http.Act;
import com.nf.health.app.sweat.activity.SweatAnalyzerNewActivity;
import com.nf.health.app.sweat.bean.ParseDataBean;
import com.nf.health.app.sweat.bean.SweatBean;
import com.nf.health.app.sweat.service.SweatServiceTwoFastBle;
import com.nf.health.app.sweat.util.SweatBluetoothUtils;
import com.nf.health.app.sweat.util.SweatConfiguration;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by he_pan on 2017/4/28.
 * The only genius that is worth anything is the genius for hard work
 *
 * @author he_pan
 * @Description 设备2汗液数据 13 路 7 路 要根据数据确定
 */

public class SweatTwoFragment extends IBaseFragment {
    @Bind(R.id.tv_hint)
    TextView tvHint;
    @Bind(R.id.tv_unit_tem)
    TextView tvUnitTem;
    @Bind(R.id.tv_unit_hum)
    TextView tvUnitHum;
    @Bind(R.id.ll_channel_name)
    LinearLayout llChannelName;
    @Bind(R.id.ll_show_data_tem)
    LinearLayout llShowDataTem;
    @Bind(R.id.ll_show_data_hum)
    LinearLayout llShowDataHum;
    private SweatAnalyzerNewActivity mActivity;
    private String address;
    private ServiceConnection mServiceConnection;
    // 蓝牙服务类
    private SweatServiceTwoFastBle mBluetoothLeService;
    private int collection_frequency = 10;//采集频率
    private ArrayList<ParseDataBean> dataList = new ArrayList<>();//存储数据,大于某个数值就上传
    private List<String> uploadStringList;//存储正在上传的数据
    private ArrayList<ParseDataBean> dataListLine = new ArrayList<>();//存储数据,用于画线,和上传池简单区分
    private int channelNum = -1;//记录此设备一共几路数据
    private int uploadType = -1;//记录类型,根据channelNum来确定
    private static final int READ_DATA = 1;
    private static final int READ_FREQ = 2;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case READ_DATA:
                    //读取数据命令
                    if (mBluetoothLeService != null) {
                        mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_READ_DATA, 10);
                        //重复读取,间隔为collection_frequency,但最少要间隔5秒
                        if (collection_frequency >= 5) {
                            removeMessages(READ_DATA);
                            sendEmptyMessageDelayed(READ_DATA, collection_frequency * 1000);
                        } else {
                            removeMessages(READ_DATA);
                            sendEmptyMessageDelayed(READ_DATA, 5 * 1000);
                        }
                    }
                    break;
                case READ_FREQ:
                    if (mBluetoothLeService != null) {
                        mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_SET_FREQ, 0);
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_sweat_down);
        ButterKnife.bind(this, rootView);
        mActivity = (SweatAnalyzerNewActivity) getActivity();
        address = PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_TWO, "");
        initView();
        if (!TextUtils.isEmpty(address)) {
            bindLeService();
        } else {
            tvHint.setText("还未绑定设备(2)");
        }

    }

    private void initView() {
        //测量部位
        List<String> positions = mActivity.getMeasurePosition();
        if (positions == null || positions.size() != 20) return;
        for (int i = 0; i < SweatBluetoothUtils.DOWN_MAX_CHANNEL; i++) {
            ((TextView) llChannelName.getChildAt(i)).setText(positions.get(i + SweatBluetoothUtils.UP_MAX_CHANNEL));
        }
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((SweatServiceTwoFastBle.LocalBinder) service).getService();
                if (mBluetoothLeService.initialize()) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mBluetoothLeService.scanMacAndConnect(address);
                        }
                    }, 3000);
                } else {
                    tvHint.setText("初始化失败...");
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(mActivity, SweatServiceTwoFastBle.class);
        mActivity.bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 所有关于蓝牙的回调都在这里
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (SweatServiceTwoFastBle.ACTION_GATT_START_SCAN_AND_CONNECT.equals(action)) {
                tvHint.setText("尝试扫描并连接...");
                mHandler.removeCallbacksAndMessages(null);//移除本地队列
            } else if (SweatServiceTwoFastBle.ACTION_GATT_CONNECTED.equals(action)) {
                tvHint.setText("连接成功,尝试获取蓝牙服务...");
            } else if (SweatServiceTwoFastBle.ACTION_GATT_DISCONNECTED.equals(action)) {
                tvHint.setText("蓝牙断开 需退出重连...");
                mHandler.removeCallbacksAndMessages(null);//移除本地队列
            } else if (SweatServiceTwoFastBle.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                //获得采样频率
                mHandler.sendEmptyMessageDelayed(READ_FREQ, 1000);
                //延时发送读取数据
                mHandler.sendEmptyMessageDelayed(READ_DATA, 3000);
                tvHint.setText("蓝牙就绪");
            } else if (SweatServiceTwoFastBle.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(SweatServiceTwoFastBle.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                try {
                    handleFrameData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            } else if (SweatServiceTwoFastBle.ACTION_GATT_DEVICE_NOT_FOUND.equals(action)) {
                tvHint.setText("未发现设备! 按电源键开启蓝牙...");
            } else if (SweatServiceTwoFastBle.ACTION_SEND_COMMAND_FAILURE.equals(action)) {
                tvHint.setText("发送命令失败!请确认蓝牙连接正常");
            }
        }

    };

    /**
     * 处理帧数据
     */

    private void handleFrameData(byte[] data) {
        //具体处理抽取,返回处理结果bean
        ParseDataBean bean = SweatBluetoothUtils.handleFrameDataTwo(data);
        int type = bean.getType();
        if (SweatConfiguration.PARSE_TYPE_ERROR == type) {//数据错误
            tvHint.setText(bean.getErrorMsg());
        } else if (SweatConfiguration.PARSE_TYPE_READ_FREQ == type) {//频率数据
            tvHint.setText("当前频率:" + bean.getFreq());
            collection_frequency = Integer.valueOf(bean.getFreq());
            //保存采集频率
            PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_FREQUENCY_TWO, bean.getFreq());
        } else if (SweatConfiguration.PARSE_TYPE_READ_DATA == type) {//温湿度数据
            tvHint.setText("读取中...");
            dataList.add(bean);
            dataListLine.add(bean);

            initLogicByChannelNum(bean);
            try {
                upLoadDataList(false);
                showDataList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获得设备通道数,并做一些逻辑处理
     */
    private void initLogicByChannelNum(ParseDataBean bean) {
        if (channelNum == bean.getChannelNum()) {
            //防止过多调用此方法
            return;
        }
        //首先先强制上传现有数据
        upLoadDataList(true);
//        //清空折线数据
//        dataListLine.clear();

        channelNum = bean.getChannelNum();
        uploadType = channelNum == SweatBluetoothUtils.DOWN_MAX_CHANNEL ?
                SweatConfiguration.UPLOAD_TYPE_DOWN : SweatConfiguration.UPLOAD_TYPE_UP;
        if (channelNum == SweatBluetoothUtils.DOWN_MAX_CHANNEL) {//7路
            for (int i = channelNum; i < SweatBluetoothUtils.UP_MAX_CHANNEL; i++) {
                llChannelName.getChildAt(i).setVisibility(View.GONE);
                llShowDataTem.getChildAt(i).setVisibility(View.GONE);
                llShowDataHum.getChildAt(i).setVisibility(View.GONE);
            }
        } else {//13路
            for (int i = 0; i < SweatBluetoothUtils.UP_MAX_CHANNEL; i++) {
                llChannelName.getChildAt(i).setVisibility(View.VISIBLE);
                llShowDataTem.getChildAt(i).setVisibility(View.VISIBLE);
                llShowDataHum.getChildAt(i).setVisibility(View.VISIBLE);
            }
        }
        initViewPositions();
    }

    private void initViewPositions() {
        //测量部位
        List<String> positions = mActivity.getMeasurePosition();
        if (positions == null || positions.size() != 20) return;
        if (channelNum == SweatBluetoothUtils.DOWN_MAX_CHANNEL) {
            for (int i = 0; i < channelNum; i++) {
                ((TextView) llChannelName.getChildAt(i)).setText(positions.get(i + SweatBluetoothUtils.UP_MAX_CHANNEL));
            }
        } else {
            for (int i = 0; i < channelNum; i++) {
                ((TextView) llChannelName.getChildAt(i)).setText(positions.get(i));
            }
        }
    }

    /**
     * 上传数据
     * isForce 是否强制上传,不管有几条
     */
    private void upLoadDataList(boolean isForce) {

        int UPLOAD_LENGTH = 50;//上传集合长度
        if (dataList.size() == 0) {
            return;
        }
        if (isForce) {
            uploadStringList = SweatBluetoothUtils.getUploadDatas(dataList, uploadType);
            dataList.clear();
            LogUtil.e("设备2数据强制上传" + uploadStringList.get(0));
        } else if (dataList.size() > UPLOAD_LENGTH) {
            uploadStringList = SweatBluetoothUtils.getUploadDatas(dataList, uploadType);
            dataList.clear();
            for (String datas : uploadStringList) {
                LogUtil.e("设备2上传数据" + datas);
                provider.AddSweatDataNew("2", datas);
            }
        }

    }

    /**
     * 根据数据来显示折线图
     */
    private synchronized void showDataList() {
        int BROKEN_LINE_NUM = 40;//折线图显示的数据点个数
        if (dataListLine.size() == 0) {
            return;
        }
        if (dataListLine.size() > BROKEN_LINE_NUM * 5) {
            dataListLine = new ArrayList<>(dataListLine.subList(dataListLine.size() - BROKEN_LINE_NUM, dataList.size()));
        }
        for (int i = 0; i < channelNum; i++) {
            ((SweatShowView) llShowDataHum.getChildAt(i)).setDataList(SweatBluetoothUtils.getHumListByChannel(dataListLine, i));
            ((SweatShowView) llShowDataTem.getChildAt(i)).setDataList(SweatBluetoothUtils.getTemListByChannel(dataListLine, i));
        }
    }

    /**
     * 设置频率命令
     *
     * @param sampleFre 采样频率
     */
    public void sendCommandToSweat(int sampleFre) {
        if (mBluetoothLeService != null) {
            mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_SET_FREQ, sampleFre);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mActivity.registerReceiver(mGattUpdateReceiver, SweatServiceTwoFastBle.makeGattUpdateIntentFilter());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        mActivity.unregisterReceiver(mGattUpdateReceiver);
        mHandler.removeCallbacksAndMessages(null);
        upLoadDataList(true);//强制上传数据
        if (mServiceConnection != null) {
            mActivity.unbindService(mServiceConnection);
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.FLAG_ADD_SWEAT.equals(actionName)) {
            showToast("阶段上传ok");
            uploadStringList = null;
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        if (Act.Flag.GET_SWEAT_SETTING_FLAG.equals(actionName)) {
            LogUtil.e("上传失败");
            //保存到数据库
            for (int i = 0; i < uploadStringList.size(); i++) {
                MeasureDataDao.saveSweatBean(new SweatBean(uploadStringList.get(i)));
            }
        }
    }

}
